package com.cp.admin.api.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cp.admin.api.entity.CodeEnum;
import com.cp.admin.api.entity.Result;
import com.cp.admin.api.utils.PKGeneratorUtils;
import com.cp.admin.modular.user.model.UserBasics;
import com.cp.admin.modular.user.model.UserOrder;
import com.cp.admin.modular.user.model.Vip;
import com.cp.admin.modular.user.service.IProductPriceService;
import com.cp.admin.modular.user.service.IUserBasicsService;
import com.cp.admin.modular.user.service.IUserOrderService;
import com.cp.admin.modular.user.service.IVipService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/charge")
@Api(value = "充值操作", tags = "充值操作")
public class ChargeController extends BaseController {
    @Autowired
    private IUserOrderService orderService;
    @Autowired
    private IUserBasicsService userService;
    @Autowired
    private IProductPriceService productPriceService;
    @Autowired
    private IVipService vipService;

    @ApiOperation("充值订单")
    @RequestMapping(value = "/chargeVip", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "账户id", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "amount", value = "金额", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "types", value = "类型 0充值豌豆 1充值vip", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "mode", value = "充值方式0微信1支付宝", dataType = "String", required = true, paramType = "query")
    })
    public Result chargeVip(Long userId, BigDecimal amount,Integer types, Integer mode) {
        if (userId == null || amount == null || mode == null|| types == null) {
            return new Result(CodeEnum.FAIL_10001);
        }
        //验证账户
        if (userService.selectById(userId) == null) {
            return new Result(CodeEnum.FAIL_10007);
        }
        //验证金额 每次充值不得少于单价
        BigDecimal price1 = productPriceService.selectById(1).getPrice();
        if (amount.compareTo(price1) < 0) {
            return new Result(CodeEnum.FAIL_10008);
        }
        //生成订单
        UserOrder order = new UserOrder();
        order.setUserId(userId);
        order.setAmount(amount);
        order.setId(PKGeneratorUtils.getInstance().nextId());
        order.setMode(mode);
        order.setStatus(0);
        order.setTypes(types);
        if (types==1){  BigDecimal price2 = productPriceService.selectById(1).getPrice();
            //根据金额和单价算出时限，有小数按进一算
            order.setTimeLimit(Integer.valueOf(amount.divide(price2, 4).setScale(0, BigDecimal.ROUND_UP).toString()));}
      if (types==0){
          BigDecimal price3 =productPriceService.selectById(2).getPrice();
          order.setChargePeasNumber(amount.multiply(price3));
      }
        order.setCreateTime(new Date());
        if (!orderService.insert(order)) {
            return new Result(CodeEnum.FAIL_10009);
        }
        return new Result(order);
    }


    @Transactional
    @ApiOperation("付款成功")
    @RequestMapping(value = "/paySuccess", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id", dataType = "String", required = true, paramType = "query")
    })
    public Result paySuccess(Long orderId) {
        if (orderId == null) {
            return new Result(CodeEnum.FAIL_10001);
        }
        UserOrder order = orderService.selectById(orderId);
        if (order == null) {
            return new Result(CodeEnum.FAIL_10010);
        }
        order.setStatus(1);
        if (orderService.updateById(order)) {
            if (order.getTypes()==1){
            Vip vip = vipService.selectOne(new EntityWrapper().eq("user_id", order.getUserId()));
                //更新vip表
                vip.setGetPeas(new BigDecimal(0));
                vip.setGetPeasToday(new BigDecimal(3.0));
                vip.setStatus(1);
                Integer remainingDays=vip.getRemainingDays() + order.getTimeLimit();
                vip.setRemainingDays(remainingDays);
                vip.setUpdateTime(new Date());
                vip.setOrderTimes(vip.getOrderTimes() + 1);
                Calendar ca = Calendar.getInstance();
                ca.add(Calendar.DATE, remainingDays);
                vip.setExpireTime(ca.getTime());
                if (vipService.update(vip, new EntityWrapper().eq("user_id", order.getUserId()))) {
                    return new Result(vip);
                }
        }
            if (order.getTypes()==0){
                UserBasics user=userService.selectById(order.getUserId());
                user.setPeasQuantity(user.getPeasQuantity().add(order.getChargePeasNumber()));
                userService.updateById(user);
                return new Result(CodeEnum.SUCCESS);
            }
        }
        return new Result(CodeEnum.FAIL);
    }


    @ApiOperation("vip每日领取豌豆")
    @RequestMapping(value = "/pickupPeas", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "String", required = true, paramType = "query")
    })
    public Result pickupPeas(Long userId) {
        if (userId==null){
            return new Result(CodeEnum.FAIL_10001);
        }
        Vip vip=vipService.selectOne(new EntityWrapper().eq("user_id",userId));
        if (vip.getStatus()==0){
            return new Result(CodeEnum.FAIL_20001);
        }
        if (vip.getStatus()==-1){
            return new Result(CodeEnum.FAIL_20002);
        }
        if(vip.getGetPeasStatus()==1){
            return new Result(CodeEnum.FAIL_20004);
        }
        UserBasics user=userService.selectById(vip.getUserId());
            BigDecimal getPeasToday=new BigDecimal(user.getContinuousLogin().floatValue()/2+3);
            vip.setGetPeasToday(getPeasToday);
            vip.setGetPeas(vip.getGetPeas().add(getPeasToday));
            vip.setGetPeasStatus(1);
        user.setPeasQuantity(user.getPeasQuantity().add(getPeasToday));
           if(!vipService.updateById(vip)||!userService.updateById(user)) {
               return new Result(CodeEnum.FAIL_20003);
           }
        return new Result(vip);
    }


    @ApiOperation("我的订单")
    @RequestMapping(value = "/myOrder", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "String", required = true, paramType = "query")
    })
    public Result myOrder(Long userId) {
        if (userId==null){
            return new Result(CodeEnum.FAIL_10001);
        }
        List<UserOrder> orders=orderService.selectList(new EntityWrapper().eq("user_id",userId));
        return new Result(orders);
    }
}
